//
//  MessagesViewController.m
//  danpin
//
//  Created by chuangjia on 29/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "MessagesViewController.h"
#import "BaseModel.h"
#import "CellConfig.h"
#import "viewconfig.h"
#import "GoodConfig.h"
#import "ShareorderConfig.h"

#import "OtherUserCenterVC.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "WebViewController.h"
#import "ZToastManager.h"
@interface MessagesViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *setcionArray;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isRefresh;
@end

@implementation MessagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
     [UMengShare event:CK_MESSAGE acc:1];
    self.isComment = YES;
    self.navTitle =@"消息中心";
    _isLoadFinished=NO;
    _currentPage=0;
    //
    self.isRefresh = YES;
    //
    if (!_setcionArray) {
        _setcionArray =[[NSMutableArray alloc] init];
    }
    //
    [self initUI];
    [self notificationManager];
//    [ZShare showAnimationView:self.view center:CGPointZero];
    [self reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)reloadData
{
    if (self.isRefresh) {
        return;
    }
    self.currentPage=0;
    self.isRefresh = YES;
    [self getRankData];
}
-(void)scrollToTop
{
//    if(_tbView)
//    {
//        [_tbView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
//    }
    [self reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.rootViewController.tabbar setHidden:NO];
    
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.rootViewController.tabbar setHidden:YES];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.tbView=nil;
    
    DLog(@"%s", __PRETTY_FUNCTION__);
}
//
//
-(void)initUI
{
    if (_tbView) {
        _tbView.dataSource=nil;
        _tbView.delegate=nil;
        _tbView=nil;
    }
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, self.view.bounds.size.width, self.view.bounds.size.height-self.navHeight-hightAuto(45)) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =[UIColor clearColor];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    
    __weak typeof (self) wSelf = self;
    [_tbView addPullToRefreshWithActionHandler:^{
        wSelf.currentPage = 0;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView startAnimating];
        wSelf.tbView.tableFooterView =nil;
//        [wSelf.tbView setShowsInfiniteScrolling:YES];
        [wSelf getRankData];
    }];
    [_tbView.pullToRefreshView setOYStyle];
    
    [_tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.tbView.infiniteScrollingView stopAnimating];
           // [wSelf.tbView setShowsInfiniteScrolling:NO];
            return;
        }
        wSelf.isRefresh =NO;
        [wSelf.tbView.infiniteScrollingView startAnimating];
        if ([wSelf.setcionArray count]==0) {
            wSelf.currentPage=(int)[wSelf.setcionArray count];
        }else{
            wSelf.currentPage=(int)[wSelf.setcionArray count]+1;
        }
        [wSelf getRankData];
       
    }];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.setcionArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=self.setcionArray.count) {
        return 0;
    }
    NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
    return [MessageCell returnCellHeight:dict];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCell *cell = (MessageCell*)[tableView  dequeueReusableCellWithIdentifier:@"MyMessageCell"];
    if(cell == nil)
    {
        cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    
    if (indexPath.row>=self.setcionArray.count) {
        return cell;
    }
    NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
    [cell showInfo:dict key:@"message" indexPath:indexPath];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row>=self.setcionArray.count) {
        return;
    }
    NSDictionary *dict =[self.setcionArray objectAtIndex:indexPath.row];
    id ware = [dict objectForKey:@"ware"];
    if (ware && [ware isKindOfClass:[NSDictionary class]]) {
        int isShaidan = [[ware objectForKey:@"is_shaidan"] intValue];
        if (isShaidan==1) {
            ShaiorderDetailViewController *good =[[ShaiorderDetailViewController alloc] init];
            good.type =-1;
            good.dictionary = ware;
            good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
            good=nil;
        }else if (isShaidan==20) {
            WebViewController *web =[[WebViewController alloc] init];
            web.titlestr = @"message";
            NSString *urlstr =[ware objectForKey:@"url"];
            web.jsonUrl = urlstr;
            [self.navigationController pushViewController:web animated:YES];
            web=nil;
            
        }else
        {
            GoodViewController *good =[[GoodViewController alloc] init];
            good.type =-1;
            good.dictionary =ware;
            good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
        }
    }
}
//
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath*)indexPath
{
    switch (type) {
        case BEventType_good:
        {
             id ware = [obj objectForKey:@"ware"];
            if (ware && [ware isKindOfClass:[NSDictionary class]]) {
                int isShaidan = [[ware objectForKey:@"is_shaidan"] intValue];
                if (isShaidan==1) {
                    ShaiorderDetailViewController *good =[[ShaiorderDetailViewController alloc] init];
                    good.type =-1;
                    good.dictionary = ware;
                    good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
                    [self.navigationController pushViewController:good animated:YES];
                    good=nil;
                }else if (isShaidan==20) {
                    WebViewController *web =[[WebViewController alloc] init];
                     web.titlestr = @"message";
                    NSString *urlstr =[ware objectForKey:@"url"];
                    web.jsonUrl = urlstr;
                    [self.navigationController pushViewController:web animated:YES];
                    web=nil;
                    
                }else
                {
                    GoodViewController *good =[[GoodViewController alloc] init];
                    good.type =-1;
                    good.dictionary =ware;
                    good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
                    [self.navigationController pushViewController:good animated:YES];
                }
            }
            
        }
            break;
        case BEventType_sunUser:
        {
            NSDictionary* send_user =[obj objectForKey:@"send_user"];
            OtherUserCenterVC *uservc =[[OtherUserCenterVC alloc] init];
            uservc.userDictionary =send_user;
            [self.navigationController pushViewController:uservc animated:YES];
        }
            break;
        default:
            break;
    }
}
-(void)notificationManager
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:[UIApplication sharedApplication]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateLoveList:)
                                                 name:@"updateLoveList"
                                               object:nil];
}
-(void)updateLoveList:(NSNotification*)notification
{
    self.currentPage=0;
    [_setcionArray removeAllObjects];
    [self getRankData];
}
-(void)applicationWillEnterForeground
{
    self.currentPage=0;
    [_setcionArray removeAllObjects];
    [self getRankData];
}
-(void)getRankData
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    __weak typeof (self) wSelf = self;
    [BaseModel massgeList:dict allowFetchCache:_isRefresh success:^(AFHTTPRequestOperation *operation, id result) {
        wSelf.isRefresh = NO;
        [wSelf parserResultObject:result];
     //   [ZShare hiddenAnimationView:wSelf.view];
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        
    //    [wSelf.tbView reloadData];
    } failure:^(NSError *error) {
        [wSelf.tbView.infiniteScrollingView stopAnimating];
        [wSelf.tbView.pullToRefreshView stopAnimating];
    //    [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
    
}
-(void)parserResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =[resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]) {
            
            if (self.currentPage==0) {
                 [self.tbView setShowsInfiniteScrolling:YES];
                if(_tbView)
                {
                    [_tbView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
                }

                self.tbView.tableFooterView =nil;
                [self.setcionArray removeAllObjects];
            }
            for (id dict in data) {
                [self.setcionArray addObject:dict];
            }
            
        }
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        if (self.isLoadFinished) {
            [self.tbView.infiniteScrollingView stopAnimating];
           
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
             [self.tbView setShowsInfiniteScrolling:NO];
        }
    }
    //end
    
    [_tbView reloadData];
}
@end
